import pandas as pd
import matplotlib.pyplot as plt
import matplotlib as mpl
import matplotlib.dates as dt
import time, datetime, calendar
from sklearn import linear_model        #表示，可以调用sklearn中的linear_model模块进行线性回归。
from matplotlib.dates import DateFormatter, MONDAY, MonthLocator, YearLocator
import numpy as np
from IPython.display import display
from dateutil.parser import parse
from linear_regression.MySQLOperator import MySQLOperator

from sklearn.linear_model import LinearRegression
from sklearn.linear_model import RANSACRegressor
from sklearn.preprocessing import PolynomialFeatures


seed = r'D:\Work\0006_美行科技\203301.汽车数字化分析\02.工程文档库\23.需求分析\237.服务运营\车辆数据（客户提供）\E10\E10车系，电池循环周衰减\2.xlsx'
op = MySQLOperator()
data = op.get_pd_avg_decay_radio_by_day("c2e811465bf549598deba09538b3f0f9")

# data = pd.read_excel(seed, header=0, sheet_name='Sheet1')
# data.head()
# data.drop(0)
# data.set_index('时间')
# pd.to_datetime(data['时间'])

# reg_data = data.groupby([pd.Grouper(key='时间', freq='w')]).mean().reset_index()
# reg_data = data.iloc[:, [0, 1]]
# print(reg_data)
#
# weeks = reg_data['时间']
# conservation = reg_data['保持率']

# pd.plotting.register_matplotlib_converters()
print(data)
y = data['conservation_rate']
x = [[i]for i in range(len(y))]
time = data['time']
print(x)

def runplt(size=None):
    plt.figure(figsize=size)
    plt.rcParams['font.sans-serif'] = ['SimHei']  # 显示中文标签
    plt.rcParams['axes.unicode_minus'] = False
    # plt.xticks(pd.date_range('2014-09-01', '2021-02-06'), rotation=90)#设置时间标签显示格式
    # plt.xticks(x, time, size=12, rotation=50)  # 设置字体大小和字体倾斜度
    plt.xlabel(u'时间')  # x轴标签
    plt.ylabel(u'保持率')
    plt.title(u'电池衰减曲线')  # 图的名称

    # plt.autofmt_xdate()
    # plt.axis(['2019-07-28', '2021-02-06', 0.8, 1.2])
    plt.grid(True)
    plt.plot(x, y, 'r')
    return plt

def regression(x,y, model):
    plt.scatter(x, y, c='blue')
    plt.plot(x, model.predict(x), color='green')
    # plt.savefig('result/Linear.png')
    plt.show()

def denoise_regression(x,y):
    ### 使用RANSAC清除异常值高鲁棒对的线性回归模型
    ransac = RANSACRegressor(LinearRegression(),
                             max_trials=100,
                             min_samples=50,
                             # residual_metric=lambda x: np.sum(np.abs(x), axis=1),
                             residual_threshold=0.8,
                             random_state=0)
    ransac.fit(x, y)
    # 可视化
    inlier_mask = ransac.inlier_mask_
    outlier_mask = np.logical_not(inlier_mask)
    line_X = np.arange(1, len(x), 1)
    line_y_ransac = ransac.predict(line_X[:, np.newaxis])
    print(inlier_mask)
    print(outlier_mask)
    print(line_y_ransac)
    # plt.scatter(x[inlier_mask], y[inlier_mask],
    #             c='blue', marker='o', label='Inliers')
    # plt.scatter(x[outlier_mask], y[outlier_mask],
    #             c='lightgreen', marker='s', label='Outliers')
    plt.plot(line_X, line_y_ransac, color='red')
    plt.show()

def fit_regression(x,y):
    # 特征构造
    poly_reg = PolynomialFeatures(degree=2)
    x_poly = poly_reg.fit_transform(x)
    # 创建线性模型
    linear_reg = LinearRegression()
    linear_reg.fit(x_poly, y)

    # plt.figure()
    plt.plot(x, y, 'b.', label="电池衰减拟合")
    # plt.legend()
    plt.ylim([0.8, 1.1])
    plt.show()

#        plt.show()

if __name__ == '__main__':
    plt = runplt()
    plt.show()

    slr = LinearRegression()
    slr.fit(x, y)
    print("Slope: %.3f" % slr.coef_[0])
    print("intercept: %.3f" % slr.intercept_)
    regression(x, y, slr)
    fit_regression(x, y)
    # denoise_regression(x, y)
